package com.uum.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.uum.admin.pojo.entity.SysPermissionRole;
import com.uum.admin.mapper.SysPermissionRoleMapper;
import com.uum.admin.pojo.form.PermissionRoleForm;
import com.uum.admin.service.SysPermissionRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uum.admin.service.SysPermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Tsang_yc
 * @since 2022-01-19
 */
@Service
public class SysPermissionRoleServiceImpl extends ServiceImpl<SysPermissionRoleMapper, SysPermissionRole> implements SysPermissionRoleService {


    /**
     * 根据菜单ID和角色ID获取权限ID集合
     *
     * @param menuId
     * @param roleId
     * @return
     */
    @Override
    public List<Long> listPermIds(Long menuId, Long roleId) {
        return this.baseMapper.listPermIds(menuId, roleId);
    }

    /**
     * 保存角色权限
     *
     * @return
     */
    @Override
    @Transactional
    public void saveRolePerms(PermissionRoleForm rolePermsForm) {
        Long menuId = rolePermsForm.getMenuId();
        Long roleId = rolePermsForm.getRoleId();
        List<Long> permIds = rolePermsForm.getPermissionIds();
        List<Long> oldPermIds = listPermIds(menuId, roleId);
        //查询出此角色该菜单下的权限 删除
        if (!oldPermIds.isEmpty()) {
            baseMapper.delete(new LambdaQueryWrapper<SysPermissionRole>()
                    .eq(SysPermissionRole::getRoleId, roleId)
                    .in(SysPermissionRole::getPermissionId, oldPermIds));
        }
        //保存新的
        if (!permIds.isEmpty()) {
            List<SysPermissionRole> rolePerms = new ArrayList<>();
            for (Long permId : permIds) {
                SysPermissionRole rolePerm = new SysPermissionRole().setRoleId(roleId).setPermissionId(permId);
                rolePerms.add(rolePerm);
            }
            this.saveBatch(rolePerms);
        }
    }


}
